package com.spring.utils.api_v4.controller;

import com.spring.utils.api_v4.annotation.ResponseResult;
import com.spring.utils.api_v4.controller.ui.DeptItem;
import com.spring.utils.api_v4.pojo.DeptInfo;
import com.spring.utils.api_v4.pojo.UserInfo;
import com.spring.utils.api_v4.service.ISystemService;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统接口
 */
@RestController
@ResponseResult
@RequestMapping("/api/sys")
@Log
public class SystemController {
    @Autowired private ISystemService systemService;

    /**
     * 查询全部部门列表
     * @return
     */
    @GetMapping("/dept/all")
    public List<DeptItem> getDeptsAll() {
       return convertDepts(systemService.getDeptsAll());
    }

    /**
     * 获取用户管理的部门列表
     * @param token
     * @return
     */
    @GetMapping("/dept/list")
    public List<DeptItem> getDeptsOfUser(@RequestHeader String token) {
        List<DeptInfo> depts = new ArrayList<>();
        UserInfo user = systemService.getUserById(token);
        // 如果用户是管理员
        if(systemService.hasRole(user, "admin")) {
            depts = systemService.getDeptsAll();
        }
        else {
            depts.add(user.getDepart());
        }
        return convertDepts(depts);
    }

    /**
     * 部门信息列表格式转换
     * @param depts
     * @return
     */
    private List<DeptItem> convertDepts(List<DeptInfo> depts) {
        return depts.stream().map(dept -> {
            // log.info(dept.getName() + "---" + dept.getStaff().size());
            DeptItem di = new DeptItem();
            BeanUtils.copyProperties(dept, di);
            return di;
        }).collect(Collectors.toList());
    }

    /**
     * 保存部门信息
     * @param deptItem
     * @return
     */
    @PostMapping("/dept/save")
    public int saveDept(@Valid @RequestBody DeptItem deptItem) {
        // 根据编号查询部门
        DeptInfo dept = systemService.getDeptById(deptItem.getId());
        if(dept == null) {
            dept = new DeptInfo();
        }
        // 复制属性
        BeanUtils.copyProperties(deptItem, dept);
        // 保存部门信息
        systemService.saveDept(dept);
        return dept.getId();
    }

    /**
     * 删除部门信息
     * @param deptId
     * @return
     */
    @DeleteMapping("/dept/delete/{deptId}")
    public boolean deleteDept(@PathVariable int deptId) {
        systemService.deleteDeptById(deptId);
        return true;
    }
}
